<template>
  <!--验证规则-->
  <nf-form
    ref="formDom"
    v-form-drag="formRuleProps"
    :model="_meta"
    :partModel="_partMeta"
    v-bind="formRuleProps"
  >
  </nf-form>
  <el-button type="" @click="add" size="mini" >保存</el-button>
  <el-button type="" @click="esc" size="mini" >取消</el-button>

</template>

<script>
  import { reactive, toRaw, ref, onMounted } from 'vue'
  import { nfForm } from '../map'

  import form_rule from '../form/json/form-rule.json'
 
  const createRule = (re, rule) => {
    
    delete re.len
    delete re.max
    delete re.min
    delete re.pattern
    delete re.type

    re.trigger = rule.trigger
    re.message = rule.message
    re.required = rule.required
    if (rule.len > 0) re.len = rule.len
    if (rule.max > 0) re.max = rule.max
    if (rule.min > 0) re.min = rule.min
    if (rule.pattern.length > 0) re.pattern = rule.pattern
    if (rule.type !== null && rule.type !== '' && rule.type !== 'any')
      re.type = rule.type
    
    return re
  }

</script>

<script setup>
  // 定义属性，接收传递来的 meta
  const props = defineProps({
    ruleModel: Object, // 验证规则的 model
    dialogInfo: Object, // 弹窗信息
    events: Object
  })

  const formDom = ref(null)
  let validate = () => {}
  onMounted(() => {
    console.log('外部表单', formDom)
    validate = formDom.value.formControl.validate
  })
  const formRuleProps = reactive(form_rule)
 
  const { ruleModel, events, dialogInfo } = props

  const _partMeta = reactive({})
  const _meta = reactive({})

  Object.assign(_meta, toRaw(ruleModel))
 
  // 添加事件
  const add = () => {
    console.log(formDom)
    validate((valid) => {
      console.log('提交时的验证', valid)
    })
    createRule(ruleModel, _meta)
    if (typeof events.add === 'function') events.add()
    dialogInfo.isShow = false
  }

  // 取消或者关闭
  const esc = () => {
    if (dialogInfo ) dialogInfo.isShow = false
  }
</script>